<!-- 按钮设置-选择商品列表 -->
<template>
	<a-modal :width='600'
    :title='modalProps.title'
    :visible="visible"
    @ok="handleOk"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel" 
    >	
	    <a-form  :form='form'  :label-col='{ span : 4}'  :wrapper-col="{ span : 16 }"  >
	    	<!-- hidden -->
	    	<a-form-item  style='display: none;'>
		    	<a-input  v-decorator='["code",formset.code]'  />
	    	</a-form-item>	

	    	<a-form-item  label='商品主题' style='margin-bottom: 0'>
		    	<a-input placeholder="商品列表主题" v-decorator='["themeName",formset.themeName]'  />
	    	</a-form-item>	
	    	<a-divider orientation="left" style='font-size: 14px;color: #999;margin:15px 0'>商品选择</a-divider>
	        <a-form-item style='margin-bottom: 0'>
		    	<a-input-search placeholder="输入搜索..." v-model='keyword'  @search="onSearch"  style='width: 200px'  /> 
	    	</a-form-item>	 
	    	<a-form-item > 
			    <!-- 多选框实现单选-->
			    <!-- checked属性在前端返回数据添加的，无需添加checkboxGroup -->
			    <a-checkbox v-for='(item,index) in category' :value="item.code"  :checked='item.checked'  @change="cateChange">
			          {{item.categoryName}}  
			    </a-checkbox>    
			</a-form-item>
		</a-form>

		已选择<span class='color-red '> {{checkedComNum}} </span>个选项 
		<a-list :grid="{ gutter: 16, column: 4 }" :data-source="data">
		    <a-list-item slot="renderItem" slot-scope="item, index">
		    	<a-checkbox :value="item.code" :checked='item.checked' @change='checkChange'>
			      <a-card :title="item.spuName">
			        Card content
			      </a-card>
			    </a-checkbox>
		    </a-list-item>
		</a-list>
		 <a-pagination  size="small"  style='text-align:right;'
		    v-model="current"
		    @change='onPageChange'
		    :page-size-options="pageSizeOptions"
		    :total="total"
		    show-size-changer

		    :page-size="pageSize"
		    :show-total="total => `共有 ${total} 件商品`"
		    @showSizeChange="onShowSizeChange"
		  >
		    <template slot="buildOptionText" slot-scope="props">
		       {{ props.value }}条/页 
		    </template>
		  </a-pagination> 
		
    </a-modal>
</template>

<script type="text/javascript">
	 const emptyString = ''
	import { commodityList,CategoryList,editCommodity_theme,getCommodity } from '@/api/minipro/commodity'
	export default{
		name:'selectCommodityOfList',
		props:{
		  visible:{
		    type:Boolean,
		    default:false
		  }, 
		},
		data(){
			return {
				/* 页面设置 */
				_isEdit:false,
				modalProps:{
					title:'选择商品'
				},    

				/* 前台展示数据 */
				category:[],//所有类别选项Array  
				data:[],//所有商品选项Array  
				pageSizeOptions: ['4','8'],//商品列表页码配置 
				checkedComNum:0,//已经选则的商品总数

				/* 后台交互数据 */
					/***交互***/
				current: 1,//页数
				pageSize: 4,
				total: null, 
				keyword:'',//搜索内容 v-model 
					/***表单项***/
				formset:{ 
   				 	code:{ initialValue: emptyString },//v-model
   				 	themeName:{ initialValue: emptyString }, //v-model
				},
				commoditySpuList:[],//已经选择的商品Array v-model
			}
		},
		beforeCreate(){
			this.form = this.$form.createForm(this)
		},	
		created(){
			this.pageInit()
			this.CommodityList()
		},
		methods:{
			pageInit(){
				//请求分类列表
				CategoryList().then((res)=>{
					let data = res.data.dataList 
					data.forEach((item)=>{//将数据加上checked字段，以便后面控制单选
						item.checked = false
					})
					this.category = data
				})
			},
			//请求所有商品列表，每次返回pageSize个商品  //promise形式为了 实现功能前保证更新data
			CommodityList(){  
				return new Promise((resolve,reject)=>{
					commodityList({pageNo:this.current,pageSize:this.pageSize,keyword:this.keyword}).then((res)=>{
						let data = res.data.dataList
						data.forEach((item)=>{//将数据加上checked字段，以便后面控制选中
							item.checked = false
						})
						this.data = data
						this.total = res.data.totalRs 
						resolve()
					})
				})
			},
			  
			/*
				输入关键词搜索商品
			*/
			onSearch(){
				this.current = 1
				this.pageSize = 4
				this.CommodityList()
			},
			/*
				选择类别搜索：checkbox多选框，控制单选
			*/
			cateChange(e){
				// console.log(e) 
				let { value } = e.target,
				 	arr       = this.category
				for( let i = 0; i < arr.length; i++){ 
					//box状态置反
					if(arr[i].code == value){
						arr[i].checked = !arr[i].checked 
						//search。。。waiting
						// if(arr[i].checked == true){
						// 	this.CommodityList({//类别id})
						// }
						continue
					}
					//其余checkbox 设置为false
					arr[i].checked = false
				}   
			},

			/*
				选择商品加入列表checkbox change
			*/
			checkChange(e){
				// console.log(e)
				/* 绑定数组变化 */
				let { value } = e.target , 
					checkArr  = this.commoditySpuList
				//选中
				if(e.target.checked == true){
					this.checkedComNum++ 
					checkArr.push({code:value})
				}
				//取消选择
				else{
					this.checkedComNum--
					for(let i = 0; i < checkArr.length; i++){
						if(value == checkArr[i].code){
							checkArr.splice(i,1)
							break;
						}
					}
				}

				/* checkbox颜色变化 */
				for(let i=0; i<this.data.length; i++){ 
					if(this.data[i].code == value){
						this.data[i].checked = !this.data[i].checked 
						continue
					} 
				} 
			},

			/*
				提交表单
			*/
			handleOk(){	
				let form = this.form.getFieldsValue(),
					url  = this._isEdit == true ? '/sys/commodity_theme/modify_commodity_theme' : '/sys/commodity_theme/create_commodity_theme'
				form.commoditySpuList = this.commoditySpuList 

				editCommodity_theme(url,form).then((res)=>{
					this.$message.success(res.data.msg)
					this.$emit('ok')  
				})
				this.setInitData()
   	
			},
			/*
				返回上一级
			*/
			handleCancel(){
				this.$emit('cancel')  
				this.setInitData()
			},

			/*
				this._isEdit = true
				当前显示的商品列表与已选商品数组对比，相同元素checked

				数据列表array2			[length:pagesize]\
				在已经选择的商品array1	[length：0~]   
				 
			*/
			selectItemToChecked(arr){   
				if(arr.length == 0){ 
					return
				} 

				let temp = []
				//列表数组在外层
				for(let i=0;i<this.data.length;i++){
					//已选数组在内层
					for(let j = 0;j<arr.length;j++){
						if(this.data[i].code == arr[j].code){
							this.data[i].checked = true 
							break
						}
					}
				}
				  
			},

			/*
				展示条数变化
			*/
			onShowSizeChange(current, size){ 
				this.pageSize = size 
				this.CommodityList().then(()=>{ //需确认data已经被更新，才能进行再次checked绑定
					this.selectItemToChecked(this.commoditySpuList) 
				})
				
			},
			/*
				展示页码改变
			*/ 
			onPageChange(page, pageSize){
				this.current = page
				this.CommodityList().then(()=>{ //需确认data已经被更新，才能进行再次checked绑定
					this.selectItemToChecked(this.commoditySpuList) 
				})
			},
			/*
				初始化
			*/
			setInitData(){
				this.current = 1
				this.pageSize = 4
				this.keyword = '' 
				this.form.setFieldsValue({code:'', themeName:''})
				this.commoditySpuList.length = 0 
				this.CommodityList() 
				this.category.forEach((item)=>{
					item.checked = false
				})
			}
		},
		mounted(){
			this.$nextTick(()=>{
				let that = this
				this.$on('openDialog',()=>{ 
					this._isEdit = false 
					
				})
				this.$on('editDialog',(code)=>{ 
					this._isEdit = true 
					 
					this.formset.code.initialValue = emptyString //initialValue只能用第一次初始化的值，当后面变的话 就不是该值了
					getCommodity(code).then((res)=>{
						let data = res.data.data
						 
						this.form.setFieldsValue({ themeName:data.themeName, code })
						this.checkedComNum                 = data.commoditySpuList.length//展示
						//checked选中变色
						this.selectItemToChecked(            data.commoditySpuList) 
						data.commoditySpuList.forEach((item)=>{ //过滤元素对象属性，只要code 
							this.commoditySpuList.push({ code: item.code })
						}) 

					})
				})
			  })
		},
		computed:{
			 
		}
		
	}
</script>